package com.example.mypra1.fragments;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.mypra1.CommentActivity;
import com.example.mypra1.R;
import com.example.mypra1.adapter.MyListAdapter;
import com.example.mypra1.adapter.entity.Comment;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.szysky.customize.siv.SImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 问答模块
 */
public class MainFragment3 extends Fragment{
    private Context mContext;
    private View rootView;
    private LinearLayout go_comment;
    private TextView count_tv;
    private List<Comment>comments = new ArrayList<>();
    private ListView listView;
    private ImageView sx;
    private Handler handler=new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            Map<String,Object>map = (Map<String, Object>) msg.obj;
            comments = (List<Comment>) map.get("comments");
            count_tv = rootView.findViewById(R.id.cmt_count);
            count_tv.setText(map.get("count").toString());
            listView = rootView.findViewById(R.id.list_view);
            MyListAdapter adapter = new MyListAdapter(mContext.getApplicationContext(),R.layout.project_item,comments){
                public void showReply(int position){//实现MyListAdapter中的抽象方法
                    //通过Bundle实现创建弹框碎片时并向它传递数据
                    Bundle bundle = new Bundle();
                    Comment comment = comments.get(position);
                    bundle.putInt("id",comment.getId());
                    bundle.putInt("rep_count",comment.getRepcount());
                    bundle.putString("profile",comment.getProfile());
                    bundle.putString("pubname",comment.getPubname());
                    bundle.putString("pubtime",comment.getPubtime());
                    bundle.putString("content",comment.getContent());
                    bundle.putString("imgs",comment.getImgs());
                    //创建底部弹框
                    BottomDialogFragment bottomDialogFragment = new BottomDialogFragment();
                    bottomDialogFragment.setArguments(bundle);//设置传递数据
                    bottomDialogFragment.show(getActivity().getSupportFragmentManager(),"tag");
                }
            };
            listView.setAdapter(adapter);
        }
    };
    public static MainFragment3 newInstance() {
        Bundle args = new Bundle();
        MainFragment3 fragment = new MainFragment3();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.main_fragment3, container, false);
        }
        sx = rootView.findViewById(R.id.sx);
        sx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getData();
            }
        });
        EventBus.getDefault().register(MainFragment3.this);//注册总线
        getData();//发送网络请求获取数据
        go_comment = rootView.findViewById(R.id.go_comment);
        go_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//跳转发布内容的活动
                Intent intent = new Intent(mContext.getApplicationContext(), CommentActivity.class);
                startActivity(intent);
            }
        });
        return rootView;
    }
    //发布-订阅者模式
    @Subscribe
    public void onEvent(int cmtid) {
        Log.d("count","hahahahah");
        getData();
    }

    //发送get请求获取帖子数据
    private void getData(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://8.142.19.67:3000/allComments")
                            .build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException,RuntimeException {
                            Log.d("resp",response.toString());
                            if (response.isSuccessful()) {
                                String res = response.body().string();
                                Log.d("res",res);
                                try {
                                    JSONObject jsonObject = new JSONObject(res);
                                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                                    int count = jsonObject.getInt("count");
                                    Log.d("array",jsonArray.toString());
                                    Map<String,Object>map = new HashMap<>();
                                    map.put("count",count);
                                    List<Comment>comments1 = new ArrayList<>();
                                    for(int i=0;i<jsonArray.length();i++){
                                        JSONObject object = jsonArray.getJSONObject(i);
                                        comments1.add(new Comment(object.getInt("id"),object.getInt("pubid"),
                                                object.getString("username"),object.getString("profile"),object.getString("content"),
                                                object.getString("imgs"),object.getString("pubtime"),object.getInt("favor"),
                                                object.getInt("repcount")));
                                    }
                                    map.put("comments",comments1);
                                    Message message = new Message();
                                    message.obj = map;
                                    handler.sendMessage(message);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }else{
                                Log.d("resp",response.toString());
                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
